package ru.ifmo.filemanager.core;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;

class PluginLoader {

	private static final String pluginsDirectory = System
			.getProperty("user.dir")
			+ java.io.File.separator + "Plugins";

	public static Boolean loadPlugins() {
		File pluginDir = new File(pluginsDirectory);

		if (!pluginDir.canRead() || !pluginDir.isDirectory())
			return false;

		for (File file : pluginDir.listFiles()) {
			try {

				if (!file.getName().endsWith(".jar")) {
					continue;
				}

				JarFile jarFile = new JarFile(file);

				Manifest manifest = jarFile.getManifest();
				
				Attributes classMetaData = manifest.getAttributes("pluginClass");

				if( classMetaData == null )
					continue;
				
				String name = classMetaData.getValue("className");
				
				if( name == null )
					continue;

				URL[] path = new URL[] { new URL("jar:file:/" + file.getAbsolutePath()
						+ "!/") };

				URLClassLoader loader = new URLClassLoader(path);

				Class<?> pluginClass = loader.loadClass(name);

				Method loadMethod = pluginClass.getMethod("load");

				loadMethod.invoke(null);

			} catch (Throwable e) {
				Core.error("Unable to load plugin from file " + file.getAbsolutePath(), e,
						true);
			}
		}

		return true;
	}
}
